// 翻译服务器
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <unordered_map>

class DictServer
{
public:
    DictServer(int port)
    :_server(&_baseloop, muduo::net::InetAddress("127.0.0.1", 9090), "DictServer", muduo::net::TcpServer::kNoReusePort)
    {
        // 设置回调函数
        _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::onMessage, this, std::placeholders::_1, std::placeholders::_2));
    }

    void start()
    {
        _server.start();    // 开始监听
        _baseloop.loop();   // 开始事件循环
    }
private:

    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
            std::cout << "连接建立 \n" << std::endl;
        else 
            std::cout << "连接断开 \n" << std::endl;
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf)
    {
        static std::unordered_map<std::string, std::string> dicts = 
        {
            {"hello", "你好"},
            {"world", "世界"}
        };

        // 获取数据
        std::string msg = buf->retrieveAllAsString();
        std::string res;
        auto it = dicts.find(msg);
        if(it != dicts.end())
            res = it->second;
        else 
            res = "not found";
        
        conn->send(res);
    }

private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    DictServer svr(9090);
    svr.start();
}